package com.bearlair.ch8;

import java.util.Random;

public class UnCaughtExceptionHandlerExample implements Runnable {

    public static void main(String[] args) {
        UnCaughtExceptionHandlerExample uncaughtExceptionHandler = new UnCaughtExceptionHandlerExample();
        Thread t = new Thread(uncaughtExceptionHandler);
        t.setUncaughtExceptionHandler(new MyException());
        t.start();
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            if (trueOrFalse()) {
                System.out.println("count:" + count);
                count++;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                throw new NullPointerException(" throw exception");
            }
        }
    }

    boolean trueOrFalse() {
        final Random random = new Random();
        int val = random.nextInt(1000);
        if (val > 500) {
            return true;
        } else {
            return false;
        }
    }

    static class MyException implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("-----Exception------");
            System.out.println("线程异常：" + t.toString());
            System.out.println("异常信息：" + e.getMessage());
        }
    }

}
